package com.Controller;

import com.Service.UserService;
import com.pojo.User;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.servlet.http.HttpSession;

@Controller
@RequestMapping("/front")
public class UserFrontController {
    @Resource
    private UserService userService;

    @GetMapping("/login")
    public String loginPage() {
        return "front/user_login";
    }

    @PostMapping("/login")
    public String doLogin(@RequestParam String username, @RequestParam String password,
                          HttpSession session, Model model) {
        User u = userService.login(username, password);
        if (u == null) {
            model.addAttribute("error","用户名或密码错误");
            return "front/user_login";
        }
        session.setAttribute("user",u);
        if (u.getStatus() == 1){
            return "redirect:/admin/product/list";
        }
        return "redirect:/front/products";
    }

    @GetMapping("/register")
    public String show() {
        return "front/register";
    }
    @PostMapping("/register")
    public String doReg(User user, Model m) {
        if (userService.exit(user.getUsername())) {
            m.addAttribute("error", "用户名已存在");
            return "front/register";
        }
        userService.register(user);
        return "redirect:/front/login";
    }
}
